

const WebSocket = require('ws')
const wss = new WebSocket.Server({
    port: 9998
})
const path = require('path')
const fileUtils = require('../utils/file_utils')
// 服务端开启了监听
module.exports.listen = () => {
    // client是客户端连接的socket
    wss.on('connection', client => {
        console.log('有客户端连接成功了....')
        client.on('message', async msg => {
            let payload = JSON.parse(msg)
            const action = payload.action
            if (action == 'getData') {
                let filePath = '../data/' + payload.charName + '.json'
                filePath = path.join(__dirname, filePath)
                const ret = await fileUtils.getFileJsonData(filePath)
                // 需要在服务端获取到数据的基础之上,增加个data字段,data对应的值就是某个json获取的值
                payload.data = ret
                client.send(JSON.stringify(payload))
            } else {
                // 原封不动的将所有收到的数据转发给每一个处于连接状态的客户端
                wss.clients.forEach(client => {
                    client.send(msg)
                })
            }
            console.log('客户端发送消息给服务端了', msg)
            // client.send('hello socket from backend')
        })
    })

}
